package com.kong.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.kong.pojo.Permission;
import com.kong.pojo.Role;
import com.kong.service .UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author yang2013
 * @data 2020/10/18 16:08
 */
@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        com.kong.pojo.User user=userService.findUserByUsername(username);
        if (user==null){
            return null;
        }
        //查询用户角色集合和权限集合
        List<GrantedAuthority> grantedAuthorities=new ArrayList<>();
        Set<Role> roles = user.getRoles();
        if (roles!=null && roles.size()>0){
            for (Role role : roles) {
                grantedAuthorities.add(new SimpleGrantedAuthority(role.getKeyword()));
                Set<Permission> permissions = role.getPermissions();
                if (permissions!=null && permissions.size()>0){
                    for (Permission permission : permissions) {
                        grantedAuthorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
                    }
                }
            }
        }
        //密码校验由权限框架完成
        String password = user.getPassword();
        return new User(username,password,grantedAuthorities);
    }
}
